package com.kfm.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.List;

@MultipartConfig(location = "d:/temp") // 上传文件必须加上这个注解
@WebServlet("/upload")
public class UploadServlet extends HttpServlet {

    List<String> imageTypes = List.of("image/jpeg", "image/png", "image/gif");

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("UploadServlet.doPost");

        // 获取参数
        String name = request.getParameter("fileName");
        System.out.println(name);
        // 获取文件
        Part img = request.getPart("img");

        // 获取文件名
        String fileName = img.getSubmittedFileName();
        System.out.println("getSubmittedFileName : " + fileName);
        String name1 = img.getName();
        System.out.println("getName : " + name1);

        // 获取文件类型
        String contentType = img.getContentType();
        System.out.println("getContentType : " + contentType);

        // 验证是否是图片
        if (!contentType.startsWith("image/")){
            System.out.println("不是图片");
            return;
        }

        if (imageTypes.contains(contentType)){
            System.out.println("是图片");
        } else {
            System.out.println("不是图片");
            return;
        }

        // 获取文件大小
        long size = img.getSize();
        System.out.println("getSize : " + size);

        // 保存文件

        // 获取项目的真实路径
        String realPath = getServletContext().getRealPath("/images");

        File file = new File(realPath);
        // 如果文件夹不存在，则创建
        if (!file.exists()){
            file.mkdirs();
        }
//        System.out.println(realPath);
//        img.write(realPath + File.separator + fileName);

        img.write("d://temp/upload" + File.separator + fileName);

        // 获取文件内容
//        InputStream inputStream = img.getInputStream();
//        System.out.println(inputStream.available());

    }
}
